﻿#if !UNITY_IOS || HUpdate
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace UnityModule
{
    public partial class DownloadComponent
    {
        private Action<int, int, long, long> m_onBgDownloadProgressEvent;
        /// <summary>
        /// 后台下载进度Action
        /// </summary>
        public event Action<int, int, long, long> OnBgDownloadProgressEvent
        {
            add
            {
                m_onBgDownloadProgressEvent -= value;
                m_onBgDownloadProgressEvent += value;
            }

            remove
            {
                m_onBgDownloadProgressEvent -= value;
            }
        }

        private Action m_onBgDownloadFinishEvent;
        /// <summary>
        /// 后台下载完成Action
        /// </summary>
        public event Action OnBgDownloadFinishEvent
        {
            add
            {
                m_onBgDownloadFinishEvent -= value;
                m_onBgDownloadFinishEvent += value;
            }

            remove
            {
                m_onBgDownloadFinishEvent -= value;
            }
        }

        /// <summary>
        /// 后台下载总大小
        /// </summary>
        public long BgTotalDownBytes { get; private set; }

        /// <summary>
        /// 后台已经接受的大小
        /// </summary>
        public long BgReceivedBytes { get; private set; }


        /// <summary>
        /// 后台下载总数量
        /// </summary>
        public int BgNeedDownloadNum { get; private set; }

        /// <summary>
        /// 已经完成的后台下载文件数量
        /// </summary>
        public int BgCompleteDownloadNum { get; private set; } = 0;

        /// <summary>
        /// 后台下载已经完成
        /// </summary>
        public bool IsBgDownloadFinished
        {
            get
            {
                return BgNeedDownloadNum <= BgCompleteDownloadNum;
            }
        }

        //开始后台下载剩余资源
        public void BackgroundDownload()
        {
            //SetStep(UpdateStepUtility.Step.BgDownloadRes);
            DownloadMonitor.Watch((int)DownloadMonitor.ReportId.FullDownloadUpdateTime);
            //取消全速下载
            IsFullSpeed = false;

            FullDownloadRes();
        }

        private void FullDownloadRes() {

            List<AssetBundleInfoV2> copy= m_bgDownloadList.ToList();
            m_bgDownloadList.Clear();
            CheckDownloadList(copy.GetEnumerator());


            BgTotalDownBytes = 0;
            BgReceivedBytes = 0;

            BgNeedDownloadNum = m_bgDownloadList.Count;
            BgCompleteDownloadNum = 0;

            if (BgNeedDownloadNum > 0)
            {
                dlWatcher.Start();
                foreach (var item in m_bgDownloadList)
                {
                    BgTotalDownBytes += item.fs;
                    AddBackgroundDownloadTask(item);
                }
            }
            else
            {
                OnBgDownloadAllFinish();
            }
        }


        /// <summary>
        /// 添加后台下载
        /// </summary>
        /// <param name="abNameWithHash"></param>
        private void AddBackgroundDownloadTask(AssetBundleInfoV2 assetBundle)
        {
            AddDownloadTask(assetBundle, OnBgDownloaded, OnBgDownloadProgress, false);
        }
        
        //后台单个下载任务完成回调
        private void OnBgDownloaded(string retAbName, string exception)
        {
            if (string.IsNullOrEmpty(exception))
            {
                //下载成功
                ++BgCompleteDownloadNum;

                CallBgDownloadProgress();
                if (BgCompleteDownloadNum == BgNeedDownloadNum)
                {
                    OnBgDownloadAllFinish();
                }
            }
            else
            {
                Debug.LogWarning("BgDownload exception: " + exception);
                //SetError(UpdateStepUtility.Step.BgDownloadResError, $"后台下载文件错误({(int)UpdateStepUtility.Step.BgDownloadResError})", exception);
            }
        }

        private void OnBgDownloadAllFinish()
        {
            Debug.Log("BgDownloadAllFinish");
            DownloadMonitor.AutoReport((int)DownloadMonitor.ReportId.FullDownloadUpdateTime);
            DownloadMonitor.CleanUp();
            dlWatcher.Stop();
            m_onBgDownloadFinishEvent?.Invoke();
        }

        //后台单个下载任务进度回调
        private void OnBgDownloadProgress(long downSize, long totalSize)
        {
            BgReceivedBytes += downSize;

            CallBgDownloadProgress();
        }

        private void CallBgDownloadProgress()
        {
            //P.D($"BgDownloadProgress:{BgReceivedBytes}/{BgTotalDownBytes}");
            m_onBgDownloadProgressEvent?.Invoke(BgCompleteDownloadNum, BgNeedDownloadNum, BgReceivedBytes, BgTotalDownBytes);
        }
    }
}
#endif